import * as crypto from "crypto";
import config from '../config'

/**
 * 高汇通支付接口
 */
export default class Pay {
  //密钥
  protected _key = '';
  // 跳转地址
  protected _url = '';
  //商户号
  protected _merchant_no = '';
  // 终端号
  protected _terminal = '';
  //加密算法
  protected _signType = 'SHA256';

  /**
   * 同步地址
   */
  public backUrl = '';
  //异步地址 
  protected _notifyUrl = '';
  /**
   * 支付金额
   */
  public amount = 0;
  /**
   * 支付单号
   */
  public orderNo: string;
  //支付类型:
  protected payType = 0;
  //sett_currency_type
  protected settCurrencyType = 'CNY';
  //currency_type 币种
  protected currencyType = 'CNY';
  //busi_code 业务代码
  protected busiCode = 'PAY';
  // 返回字符串
  protected base64_memo = 'test';
  //产品名称
  public product_name = '快捷支付';

  constructor() {
    const ghtPay = config.ghtPay;
    this._key = ghtPay.key;
    this._url = ghtPay.url;
    this._terminal = ghtPay.terminal;
    this._merchant_no = ghtPay.merchantNo;
    this._notifyUrl = config.openApi.url + 'common/Common/payCallback/ghtPayCallbackNotify';
  }
  /**
   * 获取支付地址
   */
  public getPayUrl(): string {
    let base64_memo = new Buffer(this.base64_memo).toString('base64');
    let sign = `amount=${this.amount}`;
    //if(this.bankCode) sign = `${sign}&bank_code=${this.bankCode}`;
    sign = sign + `&base64_memo=${base64_memo}&busi_code=${this.busiCode}&currency_type=${this.currencyType}&merchant_no=${this._merchant_no}&notify_url=${this._notifyUrl}&order_no=${this.orderNo}&product_name=${this.product_name}&return_url=${this.backUrl}&sett_currency_type=${this.settCurrencyType}`;
    let signs = `&sign_type=${this._signType}&terminal_no=${this._terminal}`;
    const concatSign = sign + signs + `&key=${this._key}`;
    let signMsg = crypto.createHash('sha256').update(concatSign).digest('hex');
    return `${this._url}?${sign}&sign=${signMsg}${signs}`;
  }
  /**
   * 支付结果校验
   * @param query 
   */
  public verifyPayresult(query: any) {
    const sign = query.sign;
    delete query.sign;
    let besign = '';
    for (let index in query) {
      besign = `${besign}${index}=${query[index]}&`
    }
    besign = `${besign}key=${this._key}`;
    return crypto.createHash('sha256').update(besign).digest('hex') == sign;
  }

}